﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace SimpleHttpServer
{
    public interface ITFormat<T>
    {
        string Format(T item, string key);
    }

    public class Route<T> where T : class
    {
        private List<string> _RouteFormats = new List<string>();
        private Dictionary<string, T> _RouteMapping = new Dictionary<string, T>();

        public ITFormat<T> Format { get; set; }

        public Route()
        {
        }

        public void Register(T item)
        {
            if (Format == null)
                throw new Exception("not found format");

            Regex regex = new Regex("\\{(?<FormatItemName>[\\S]+?)\\}");

            foreach (var rFormat in _RouteFormats)
            {
                var fItems = regex.Matches(rFormat);
                if (fItems == null || fItems.Count == 0)
                    continue;

                var key = rFormat;
                foreach (Match fItem in fItems)
                {
                    var fSub = Format.Format(item, fItem.Groups["FormatItemName"].Value);
                    key = key.Replace($"{{{fItem.Groups["FormatItemName"].Value}}}", fSub);
                }

                if (key.IndexOfAny(new char[] { '{', '}' }) > 0)
                    continue;

                RegisterWithKey(key, item);
            }
        }

        public void RegisterWithKey(string key, T item)
        {
            _RouteMapping[key] = item;
        }

        public void AddRouteFormat(string format)
        {
            _RouteFormats.Add(format);
        }

        public T Find(string key)
        {
            return _RouteMapping.TryGetValue(key, out var value) ? value : default(T);
        }
    }
}
